<template>
  <div class="bigBox">
    <h1>图片上传</h1>
    <hr>
    <div>
      <el-form @submit.prevent="uploadFile">
        <div class="innerBox">
          <label for="image-input">选择文件：</label>
          <input type="file" id="image-input" @change="onFileChange" required multiple />
        </div>
        <div class="innerBox">
          <label for="latitude-input">经度：</label>
          <input id="latitude-input" v-model="form.latitude" required style="width:200px;height:30px" @input="validateLatitude"/>
        </div>
        <div class="innerBox">
          <label for="longitude-input">纬度：</label>
          <input id="longitude-input" v-model="form.longitude" required style="width:200px;height:30px" @input="validateLongitude"/>
        </div>
        <button type="submit" style="margin:10px;border: 1px solid #000000;border-radius: 20px;padding:5px;width:60px;height:30px">提交</button>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus';
import { defineComponent, ref } from 'vue';
import axios, { AxiosResponse } from 'axios';

const instance = axios.create({
  baseURL: 'http://172.19.0.82:8088'
})

export interface UploadForm {
  image?: File[];
  latitude?: number;
  longitude?: number;
}

export default defineComponent({
  name: 'FileUploadComponent',
  setup() {
    const form = ref<UploadForm>({
      image: [],
      latitude: undefined,
      longitude: undefined
    });

    const validateLatitude = (event: Event) => {
      const target = document.getElementById('latitude-input') as HTMLInputElement;
      const value = target.value;
      // 允许数字和一个小数点
      if (/^\d*\.?\d*$/.test(value)) {
        form.value.latitude = parseFloat(value);
      } else {
        target.value = form.value.latitude?.toString() || '';
      }
    };

    const validateLongitude = (event: Event) => {
      const target = document.getElementById('longitude-input') as HTMLInputElement;
      const value = target.value;
      // 允许数字和一个小数点
      if (/^\d*\.?\d*$/.test(value)) {
        form.value.longitude = parseFloat(value);
      } else {
        target.value = form.value.longitude?.toString() || '';
      }
    };

    const onFileChange = (event: Event) => {
      const target = event.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        form.value.image = Array.from(target.files);
      }
    };

    const uploadFile = async () => {
      if (form.value.image && form.value.image.length > 0) {
        for (let i = 0; i < form.value.image.length; i++) {
          const formData = new FormData();
          formData.append('image', form.value.image[i]);
          formData.append('latitude', form.value.latitude?.toString() || '');
          formData.append('longitude', form.value.longitude?.toString() || '');

          try {
            const response: AxiosResponse = await instance.post('/edge/upload_image', formData, {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            });
            console.log(`File ${i + 1} uploaded successfully:`, response.data);
            ElMessage.success(`第${i + 1}张图片上传成功`);
          } catch (error) {
            console.error(`Error uploading file ${i + 1}:`, error);
            ElMessage.error(`第${i + 1}张图片上传失败`);
          }
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
    };

    return {
      form,
      onFileChange,
      uploadFile,
      validateLatitude,
      validateLongitude
    };
  }
});
</script>

<style lang="scss">
.bigBox {
  margin: 24px 21px 0px 21px;
  border: 1px solid #ffffff;
  border-radius: 10px;
  padding: 20px;
  background: #fcfcfc;
}
.innerBox {
  margin:10px;
}
.inner {
  text-align: center;
}
</style>